<?php

App::uses('RedisUtility', 'Utility');

class RedisCacheBehavior extends ModelBehavior {
    
    private $ttl = 86400;
    
    public $_defaults = array('key' => 'id', 'value_key' => '');
    
    public function setup(Model $model, $config = array()) {
        
        
        $this->settings[$Model->alias] = array_merge($this->_defaults, $config);
    }
    
    // 　Key-HashMap
    public function afterSave( Model $Model, $created ) {
  
        if($Model->id){            
            $cache_key = $Model->alias.'_'.$Model->{$this->settings[$Model->alias]['key']};
            if( empty($this->settings[$Model->alias]['value_key']) ) {
                RedisUtility::setex($cache_key, $Model->data,$this->ttl);
            }
            else{
                RedisUtility::setex($cache_key, $Model->data[ $this->settings[$Model->alias]['value_key'] ],$this->ttl);
            }
        }
        return true;    
    }
    
    public function readCache($key) {
        return RedisUtility::get($Model->alias.'_'.$key);
    }
}